import { makeAutoObservable } from 'mobx';
import { Knowledge, KnowledgeFormValues } from './vectorTypes';
import { getKnowledgeList, createKnowledge, updateKnowledge, getInfo, deleteKnowledge } from '../../../../apis/backhub/knowledge';
import { message } from 'antd';

class KnowledgeStore {
  baseId: string;
  knowledges: Knowledge[] = [];
  modalVisible = false; // 弹窗显示状态
  editingKnowledge: Knowledge | undefined = undefined; // 当前编辑的向量知识库，undefined表示新建
  loading = false;

  constructor() {
    makeAutoObservable(this);
  }

  // 获取向量知识库列表
  fetchKnowledges = async (id) => {
    this.loading = true;
    try {
      this.baseId = id;
      const response = await getKnowledgeList(id);
      this.knowledges = (response as any)?.data;
    } catch (error) {
      console.error('获取向量知识库列表失败:', error);
    } finally {
      this.loading = false;
    }
  };

  // 显示创建弹窗
  showCreateModal = () => {
    this.editingKnowledge = undefined;
    this.modalVisible = true;
  };

  // 显示编辑弹窗
  showEditModal = (vector: Knowledge) => {
    this.getKnowledge(vector.id);
    this.modalVisible = true;
  };

  // 隐藏弹窗
  hideModal = () => {
    this.modalVisible = false;
    this.editingKnowledge = undefined;
  };

  //获取模型
  getKnowledge = async (id: string) => {
    try {
      this.loading = true;
      const response = await getInfo(id);
      this.editingKnowledge = (response as any).data;
      return this.editingKnowledge; // 返回获取到的用户数据
    } catch (error) {
      console.error('获取用户失败:', error);
      throw error;
    } finally {
      this.loading = false;
    }
  };

  // 保存向量知识库
  saveKnowledge = async (values: KnowledgeFormValues) => {
    try {
      if (this.editingKnowledge && this.editingKnowledge.id) {
        const response = await updateKnowledge(this.editingKnowledge.id, values);
        if((response as any)?.status){
          message.success('保存成功');
          this.fetchKnowledges(values.baseId);
        }
      } else {
        const response = await createKnowledge(values);
        if((response as any)?.status){
          message.success('创建成功');
          this.fetchKnowledges(values.baseId);
        }
      }
      this.hideModal();
    } catch (error) {
      console.error('保存向量知识库失败:', error);
    }
  };

  // 删除向量知识库
  deleteKnowledge = async (id: string) => {
    try {
      const response = await deleteKnowledge(id);
      if((response as any)?.status){
        message.success('删除成功');
        this.fetchKnowledges(this.baseId);
      }
    } catch (error) {
      console.error('删除向量知识库失败:', error);
    }
  };
}

export const knowledgeStore = new KnowledgeStore();